05 / 05

5. How would you implement optimistic UI updates for POST/DELETE using RTK Query or Thunk?

Implementing Optimistic UI Updates in RTK Query and Thunks

Optimistic UI updates make the application feel faster by updating the UI immediately before the server confirms the change. If the request fails, the state is rolled back to its previous value. Both RTK Query and createAsyncThunk can handle optimistic updates, though RTK Query simplifies the process through its built-in onQueryStarted lifecycle method.

Optimistic Updates Using RTK Query
  1. 1

    1. Use onQueryStarted: Inside a mutation endpoint, perform temporary cache updates before the server response.

  2. 2

    2. Update Query Data: Use api.util.updateQueryData() to modify the cache for the relevant query.

  3. 3

    3. Rollback on Error: Use the patchResult.undo() method if the mutation fails to revert the UI state.

Example: RTK Query Optimistic Update for DELETE
Optimistic Updates Using createAsyncThunk
  1. 1

    1. Dispatch an Immediate State Change: Update the local slice before the API call resolves.

  2. 2

    2. Handle Errors Gracefully: Revert to the old state in the rejected reducer case if the request fails.

Example: Optimistic Update with createAsyncThunk

RTK Query is ideal for optimistic updates because it handles cache invalidation and rollback automatically. Thunks are more flexible for custom logic but require manual state management. The choice depends on whether your data flow is cache-based (RTK Query) or business logic–driven (Thunk).